import axios from 'axios'
//import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import store from '@/store'
import message from '@/utils/prototype/Notifications/Notifications.js'

// 创建 axios 实例
const request = axios.create({
  baseURL:"", //这里应当置为实际部署的后端的url
  timeout: 10000, // 请求超时时间,
  withCredentials: true,
})

// 异常拦截处理器
const errorHandler = (error) => {
  console.log('errorHandler', error)
  if (error.response) {
    const data = error.response.data
    if (error.response.status === 403) {
      message.error({
        message: '403 Forbidden. ' + data.message,
      })
    }
    if (error.response.status === 500) {
      message.error({
        message: '500 Internal Server Error. ' + data.message,
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  //向请求头中插入jwt TODO 记得在登录时更新token
  let token = store.state.token;
  if(token){
    axios.defaults.headers.common["token"] = token;
  }else {
    axios.defaults.headers.common["token"] = null;
  }
  return config;
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  //将返回的静态资源地址替换为服务器地址
  let localhost = "127.0.0.1"
  let target = "10.2.4.14"

  // 判断接口返回内容内的成功标志是否为真，待后端重构后确定，现在暂时为永真
  if(response.data != null)
    response.data = JSON.parse(JSON.stringify(response.data).replace(localhost,target))
  else
    response = JSON.parse(JSON.stringify(response).replace(localhost,target))
  return Promise.resolve(response.data || response)
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
